package com.code.ContactAdvantage;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.URI;
import java.net.URISyntaxException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Locale;
import java.util.Map;

import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;

import com.code.SleepAlarm.R;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.database.Cursor;

import android.location.Address;
import android.location.Geocoder;
import android.location.Location;
import android.location.LocationManager;

import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.provider.ContactsContract;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;

public class ContactAdvantage extends Activity implements OnClickListener
{
    public static Map<String, StateInfo> stateToContact;
	public static ArrayList<String> allNames;
	public static ArrayList<String> allNumbers;
	public static ArrayList<String> allStates;
	public static ArrayList<Contact> allContacts;
	public static String requestString = new String();
	
	public static Context context;
	
	public Button GPS;
	public Button State;
	public TextView Processing;
	public static String screen = "screen1";
	public static String[] nearbyNames;
	public static String myState = "MA";
	
    public void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.screen1);
        
        context = this.getApplicationContext(); 
        
        GPS = (Button)this.findViewById(R.id.GPS);
        GPS.setOnClickListener(this);
        State = (Button)this.findViewById(R.id.State);
        State.setOnClickListener(this);
        Processing = (TextView)this.findViewById(R.id.processing);
        
        this.setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
        
        new RefreshContactThread(handler).execute((Void[])null);
        
        LocationManager lm = (LocationManager)getSystemService(Context.LOCATION_SERVICE);
        Location location = null;
        
        if (lm.isProviderEnabled(LocationManager.NETWORK_PROVIDER))
        	location = lm.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
        
        double lat = location.getLatitude();
        double longi = location.getLongitude();
        
        Log.e(lm.isProviderEnabled(LocationManager.NETWORK_PROVIDER)+"", ""+location.getLatitude());
        Log.e(lm.isProviderEnabled(LocationManager.NETWORK_PROVIDER)+"", ""+location.getLongitude());
        
        List<Address> allAddresses = this.getAddressesFromLatLong(lat, longi);
        
        for(Address a:allAddresses)
        {
        	GPS.setText(a.getAdminArea());
        }
    }

    final Handler handler = new Handler()
    {
        public void handleMessage(Message msg)
        {
            GPS.setEnabled(true);
            State.setEnabled(true);
            Processing.setVisibility(4);
        }
    };

    private class RefreshContactThread extends AsyncTask<Void, Integer, Integer>
    {
        Handler mHandler;
       
        RefreshContactThread(Handler h)
        {
            mHandler = h;
        }
		public void run()
		{
	        stateToContact = new HashMap<String, StateInfo>();
	        allNames = new ArrayList<String>();
	        allNumbers = new ArrayList<String>();
	        allStates = new ArrayList<String>();
	        allContacts = new ArrayList<Contact>();
	        
			grabAllContacts();
			Log.e("status", "got all contacts");
			
			String Json;
			try {
				Json = httpPost(requestString);
				Json = Json.replace("[", "");
				Json = Json.replace("]", "");
				Json = Json.replace("\"", "");
				Log.e("json", Json);
				String[] states = Json.split(",");
				
				for(int a = 0;a<states.length;a++)
				{
					allStates.add(states[a].trim().toUpperCase());
				}//now we should have three lists of even length!
			}
			catch (URISyntaxException e)
			{
				e.printStackTrace();
			}
			StateInfo newState;
			for(int a = 0;a<allNames.size();a++)
			{
				String state = allStates.get(a);
				if (stateToContact.containsKey(state))
				{
					newState = stateToContact.get(state);
				}
				else
				{
					newState = new StateInfo();
				}
				newState.add(allNames.get(a), allNumbers.get(a));
				Log.e("state-in", state+allNames.get(a)+allNumbers.get(a));
				stateToContact.put(state, newState);
			}
            
        }
		protected void onPostExecute(Integer arg0)
		{
			Message msg = mHandler.obtainMessage();
            msg.arg1 = 0;
			mHandler.sendMessage(msg);
	    }
		@Override
		protected Integer doInBackground(Void... params) 
		{
			this.run();
			return new Integer(5);
		}
    }

    public void onClick(View v)
    {
    	if (v == GPS)
    	{
        	Intent myIntent = new Intent(this.getApplicationContext(), OurListActivity.class);
        	myIntent.putExtra("state", "Massachusetts");
        	myIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        	context.startActivity(myIntent);
    	}
    	if (v == State)
    	{
        	Intent myIntent = new Intent(this.getApplicationContext(), StateListActivity.class);
        	myIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK); 
        	context.startActivity(myIntent);
    	}
	}
    
    
    public List<Address> getAddressesFromLatLong(double lat, double longi)
    {
    	Geocoder geocoder = new Geocoder(this, Locale.getDefault());
        try
        {
			List<Address> addresses = geocoder.getFromLocation(lat, longi, 1);
			return addresses;
        }
        catch(Exception e)
        {
        	
        }
        return null;
    }

	public String httpPost(String requestString) throws URISyntaxException
	{
		BufferedReader in = null; 
		try
		{
			HttpClient client = new DefaultHttpClient();
			HttpPost request = new HttpPost(new URI("http://reptrackerservice.appspot.com/getvalue"));
			List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2);
			nameValuePairs.add(new BasicNameValuePair("tag", requestString));
			request.setEntity(new UrlEncodedFormEntity(nameValuePairs));
			Log.e("request", requestString);
			HttpResponse response = client.execute(request);
			Log.e("http response code", response.getStatusLine().getStatusCode()+"");
			in = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));
			StringBuffer sb = new StringBuffer("");
			String line = ""; 
			String NL = System.getProperty("line.separator");
			while ((line = in.readLine()) != null) 
			{
				sb.append(line + NL);
			}

			in.close();

			String page = sb.toString();
			Log.e("page", page);
			return page;
		}
		catch (ClientProtocolException e)
		{
			e.printStackTrace();
		}
		catch (IOException e){
			e.printStackTrace();
		}
		finally
		{
			if (in != null)
			{
				try
				{
					in.close();
				}
				catch (IOException e)
				{
					e.printStackTrace();
				}
			}
		}
		return null;
	}

    public void grabAllContacts()
    {
    	allNames = new ArrayList<String>();
    	allNumbers = new ArrayList<String>();
    	allStates = new ArrayList<String>();
    	requestString = new String();
    	
    	StringBuilder sb = new StringBuilder("[");
    	
    	Cursor cursor = getContentResolver().query(ContactsContract.Contacts.CONTENT_URI,null, null, null, null); 
        while (cursor.moveToNext())
        { 
           String contactId = cursor.getString(cursor.getColumnIndex(ContactsContract.Contacts._ID));
           String name = cursor.getString(cursor.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME));
           String hasPhone = cursor.getString(cursor.getColumnIndex(ContactsContract.Contacts.HAS_PHONE_NUMBER)); 
           if (hasPhone.equals("1"))
           {
              // You know it has a number so now query it like this
              Cursor phones = getContentResolver().query( ContactsContract.CommonDataKinds.Phone.CONTENT_URI, null, ContactsContract.CommonDataKinds.Phone.CONTACT_ID +" = "+ contactId, null, null); 
              
              while (phones.moveToNext())
              { 
                 String phoneNumber = phones.getString(phones.getColumnIndex( ContactsContract.CommonDataKinds.Phone.NUMBER));  
				 
                 String number = phoneNumber;
                 number = number.replace("+", "");
     			 number = number.replace("-", "");
     			 number = number.replace("(", "");
     			 number = number.replace(")", "");
     			 number = number.replace(" ", "");
     			 if (number.charAt(0)=='1')
     			 {
     			 	number = number.substring(1);
     			 }
				 allNumbers.add(number);
				 allNames.add(name);
				 sb.append("\'");
     			 sb.append(number.substring(0, 3));
     			 sb.append("\',");
              }
              phones.close();
           }
        }
        requestString = sb.toString();
        requestString = requestString.substring(0, requestString.length()-1)+"]";
        cursor.close(); 
    }

	public class Contact implements Comparable<Contact>
	{
		String name;
		String number;

		public Contact(String name2, String number2)
		{
			name = name2;
			number = number2;
		}
		public int compareTo(Contact y)
		{
			return this.name.compareTo(y.name);
		}		
	}
	
	public class StateInfo
	{
		ArrayList<String> names;
		ArrayList<String> numbers;
		ArrayList<Contact> contacts;
		
		public StateInfo(){
			this.names = new ArrayList<String>();
			this.numbers = new ArrayList<String>();
			this.contacts = new ArrayList<Contact>();
		}
		
		public void add(String name, String number){
			this.names.add(name);
			this.numbers.add(number);
			this.contacts.add(new Contact(name, number));
		}
	}
}